package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.constants.FollowBehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    ApUserFollowMapper apUserFollowMapper;
    @Autowired
    ApUserFanMapper apUserFanMapper;
    @Autowired
    KafkaTemplate kafkaTemplate;
    /**
     * 关注与取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto==null || dto.getAuthorId()==null || dto.getOperation()<0 || dto.getOperation()>1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //远程调用查author
        ApAuthor author = articleFeign.findById(dto.getAuthorId());
        if (author==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"关注用户不存在");
        }
        //当前线程拿到用户id判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据操作。对这个作者增加粉丝，对当前用户增加关注，或者取关
        if (dto.getOperation()==0){
            return followByUserId(user.getId(),author.getUserId(),dto.getArticleId());
        }else {
            return followCancelByUserId(user.getId(),author.getUserId());
        }
    }

    /**
     *取消关注
     * @param userId 当前用户
     * @param authorId 作者
     * @return
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer authorId) {
        apUserFanMapper.delete(
                Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId,userId)
                .eq(ApUserFan::getUserId,authorId)
        );
        apUserFollowMapper.delete(
                Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId,userId)
                .eq(ApUserFollow::getFollowId,authorId)
        );
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 关注作者
     * @param userId 当前用户
     * @param authorId 关注作者
     * @param articleId
     * @return
     */
    private ResponseResult followByUserId(Integer userId, Integer authorId, Long articleId) {
        ApUser author = apUserMapper.selectOne(
                Wrappers.<ApUser>lambdaQuery()
                        .eq(ApUser::getId, authorId)
        );
        if (author==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"作者不存在");
        }
        if (author.getId().intValue()==userId.intValue()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"不能关注自己");
        }
        //往表格中封装数据插入  我的关注
        ApUserFollow apUserFollow=apUserFollowMapper.selectOne(
                Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId,authorId)
                .eq(ApUserFollow::getUserId,userId)
        );
        if (apUserFollow!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已关注该作者");
        }
        /*apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(authorId);
        apUserFollow.setUserId(userId);
        apUserFollow.setLevel((short)1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setFollowName(author.getName());
        apUserFollow.setCreatedTime(new Date());*/
        apUserFollow=ApUserFollow.builder()
                .followId(authorId)
                .userId(userId)
                .level((short) 1)
                .isNotice(true)
                .followName(author.getName())
                .createdTime(new Date())
                .build();
        apUserFollowMapper.insert(apUserFollow);

        //封装插入，作者的粉丝(可能粉丝已存在)
        ApUserFan fan = apUserFanMapper.selectOne(
                Wrappers.<ApUserFan>lambdaQuery()
                        .eq(ApUserFan::getFansId, userId)
                        .eq(ApUserFan::getUserId,authorId)
        );
        if (fan!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"粉丝已存在");
        }
        /*ApUserFan apUserFan = new ApUserFan();
        apUserFan.setUserId(authorId);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setLevel((short)0);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsDisplay(true);
        apUserFan.setFansId(userId.longValue());
        ApUser apUser = apUserMapper.selectById(userId);
        apUserFan.setFansName(apUser.getName());*/
        ApUser apUser = apUserMapper.selectById(userId);
        fan=ApUserFan.builder()
                .userId(authorId)
                .createdTime(new Date())
                .level((short) 0)
                .isShieldComment(false)
                .isShieldLetter(false)
                .isDisplay(true)
                .fansId(userId.longValue())
                .fansName(apUser.getName())
                .build();
        apUserFanMapper.insert(fan);

        //记录用户行为  发送卡夫卡消息
        FollowBehaviorDto behaviorDto = FollowBehaviorDto.builder()
                .articleId(articleId)
                .userId(userId)
                .followId(authorId)
                .build();
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(behaviorDto));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
